#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''eof
name:经营年限
code:EG_OpenDuration
tableName:
columnName:
groups:企业通用
dependencies:EG
type:常用指标
dataSourceType:在线指标
description:
eof'''

import sys
import pandas as pd
import datetime
from dateutil.relativedelta import  relativedelta

reload(sys)
sys.setdefaultencoding('utf-8')


def OperationPeriod():
    try:
        jbxx = EG['srcData'][0]['EG']['results'][0]['jbxx']

        if Formate(jbxx['esdate']) is not None:
            esdate = datetime.datetime.strptime(Formate(jbxx['esdate']), '%Y-%m-%d')
            r = relativedelta(datetime.datetime.now(), esdate)
            operation_date = r.years + r.months/float(12) + r.days/float(365)
            return round(float(operation_date), 4)
        else:
            return u'缺失值'
    except:
        return u'缺失值'


def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y-%m-%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y-%m-%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y-%m-%d')
                except:
                    date = None
    return date


result = OperationPeriod()
